package IMEI;
#use lib "/data/tools/repository/perl-5.8.8/lib/site_perl/5.8.8/";
use strict;
use warnings;

#use POSIX qw(strftime);

#use File::Basename;
#use File::stat;
use Data::Dumper 'Dumper';
#use DBI;
use Connect;

sub isLuhn
{
    my $string = shift @_;
    my($sum,$odd);
    
    foreach my $n (reverse split(//,$string)) {
        $odd=!$odd;
        if($odd) {
	    $sum+=$n;
        } else {
	    my $x=2*$n;
	    $sum+=$x>9?$x-9:$x;
        }
    }
    
    my $ok = 0+(($sum%10)==0);
    return $ok;
}

#sub dbConnect
#{
   # my $dbh = DBI->connect("DBI:mysql:database=simgen;host=localhost",
			   #"root", "Admin01ME!",
			   #{'RaiseError' => 0});
    
    #return ($dbh);
#}

#sub dbDisconnect
#{
    #my $dbh=shift @_;
    #$dbh->disconnect();
#}

sub decipherData
{
    #my $imei = shift @_;
    my $hRefEncipheredData = shift @_;
    my $hRefDecipheredData = shift @_;
    my $socket=0;
    my $proto="tcp";
    #my $peeraddr="172.24.61.137";
    my $peeraddr="127.0.0.1";
    #my $peeraddr="172.24.3.244";
    my $peerport="30000";

    #print ">get_deciphered_data<";
    if (! Connect::slsecd_connect(\$socket,\$proto,\$peeraddr,\$peerport))
    {
	print "[ERROR] Failed to connect to slsecd.\n";
	return 0;
    }

    foreach my $key (keys %$hRefEncipheredData)
    {
	#print { $h_ref_param->{SOCKET} } "D;" .$thekey. ";" .$h_ref_enciphered_keys->{$thekey}. "\n";
	print $socket "D;" .$key. ";" .$hRefEncipheredData->{$key}. "\n";
    
	$hRefDecipheredData->{$key} = <$socket>;
	
    }    

    print $socket "Q\n";
    if (! Connect::slsecd_disconnect(\$socket))
    {
	print "[WARNING] Failed to disconnect from slsecd.\n";
    }
    
    return 1;
}

sub getEncipheredData
{
    my $dbh=shift @_;
    my $string=shift @_;
    my $res="";
    my $sth;
    my $sql="";
    my $ref;

    #my $dbh=dbConnect;
    #my $dbh=Connect::db_con($hRefParam->{DBNAME},$hRefParam->{DBLOGIN},$hRefParam->{DBPASSWD});
    #print $dbh;
	
   # check whether imei exists in DB with data
    $sth = $dbh->prepare("select count(*) from imei where imei='$string' and data!='0'");
    $sth->execute();
    $ref = $sth->fetchrow_hashref();
    $sth->finish();

    if ($ref->{'count(*)'} != 0)
    {
	#print "imei ".$imei." found in DB with data\n";
	$sth = $dbh->prepare("select data from imei where imei='$string' and data!='0'");
	$sth->execute();
	$ref = $sth->fetchrow_hashref();
	$sth->finish();
	$res=$ref->{'data'};
	#Connect::db_discon($dbh);
	return $res;
    }
    
    #print "imei ".$imei." found in DB without data\n";
    $res="KO";
    #Connect::db_discon($dbh);
    return $res;
}

sub exists
{
    my $string=shift @_;
    my $res="";
    my $sth;
    my $sql="";
    my $ref;
    my $dbh=shift @_;

    #my $dbh=dbConnect;
    #my $dbh=Connect::db_con($hRefParam->{DBNAME},$hRefParam->{DBLOGIN},$hRefParam->{DBPASSWD});
    #print $dbh;
	
    # check whether imei exists in DB with data
    $sql="select count(*) from imei where imei='$string'";
    #print $sql."\n";
    $sth = $dbh->prepare($sql);
    $sth->execute();
    $ref = $sth->fetchrow_hashref();
    $sth->finish();
    
    if ($ref->{'count(*)'} == 0)
    {
	# imei not found
	#Connect::db_discon($dbh);
	  return 0;
      }
    
    return 1;
}

sub isNumeric
{
    my $string = shift @_;
    #print $hRefParam->{IMEI}."\n";

    if ($string!~/^(\d{15})$/)
    {
	#bad format
	return 0;
    }

    return 1;
}

sub isAlcatelProduct
{
    my $string = shift @_;
    my $file = shift @_;
    my $item = "";
    my $tac = "";
    my @list = ();
    my $counter = 0;

    $string=~/^(\d{6})(\d{2})(\d{6})(\d{1})/;
    $tac=$1;
    
    if(! -f $file)
    {
	return 0;
    }

    open(FILE, "<$file");
    @list = <FILE>;
    
    foreach $item (@list)
    {
	chomp($item);    
	if ($tac == $item)
	{
	    $counter++;
	}
    }
    if ($counter == 0)
    {
	#not a t&a mobile phone
	return 0;
    }

    return 1;
}

sub isOwner
{
    my $string = shift @_;
    my $requester = shift @_;
    my $dbh=shift @_;

    my $sth;
    my $sql="";
    my $ref;
    my $customerCode="";
    my $filter="";
    my $counter=0;
    
    $sql="SELECT * FROM `imei` AS a LEFT JOIN `event` AS b ON a.event_id = b.id LEFT JOIN `opl` AS c ON b.data = c.id WHERE imei='$string'";
    $sth = $dbh->prepare($sql);
    $sth->execute();
    $ref = $sth->fetchrow_hashref();
    $sth->finish();
    my $refCom=$ref->{'ref_com'};
    my $data=$ref->{'data'};
    #print "data: ".$data."\n";

    if ($data == 0)
    {
	# opl not found - commercial reference not found - filter disabled
	return 1;
    }
    
    # extracting customer code 
    # $refCom="C701X-2ARGES1";
    $refCom=~/[^-]+-\d{1}.([A-Z][A-Z]).+/;
    $customerCode=$1;
    #print $customerCode."\n";

    # matching customer code with filter
    $sql="SELECT count(*) FROM `filter` WHERE `group` = '$requester'";
    $sth = $dbh->prepare($sql);
    $sth->execute();
    $ref = $sth->fetchrow_hashref();
    $sth->finish();

    if ($ref->{'count(*)'} == 0)
    {
	# group not found
	return 0;
    }

    $sql="SELECT filter FROM `filter` WHERE `group` = '$requester'";
    #print $sql;
    $sth = $dbh->prepare($sql);
    $sth->execute();

    while($ref = $sth->fetchrow_hashref())
    {
	$filter=$ref->{'filter'};
	#print "filter: ".$filter." -> customerCode: ".$customerCode."\n";
	if($filter eq "N/A")
	{
	    # filter disabled
	    #print "filter: ".$filter."\n";
	    return 1;
	}
	if($filter eq $customerCode)
	{
	    #print "filter: ".$filter."\n";
	    $counter++;
	}
    }

    $sth->finish();
    
    #print "counter: ".$counter."\n";
    if ($counter == 0)
    {
	# requester not owner
	return 0;
    }

    return 1;
}

sub isLocked
{
    my $string = shift @_;
    my $file = shift @_;
    my @list = ();
    my $item = "";
    my $sth;
    my $sql="";
    my $ref;
    my $name="";
    my $customerCountry="";
    my $simlock="";
 
    my $dbh=shift @_;

    if(! -f $file)
    {
	return 0;
    }

    # check whether imei exists in DB with data
    $sql="SELECT count(*) FROM `imei` AS a LEFT JOIN `event` AS b ON a.event_id = b.id LEFT JOIN `opl` AS c ON b.data = c.id WHERE imei='$string'";
    #print $sql."\n";
    $sth = $dbh->prepare($sql);
    $sth->execute();
    $ref = $sth->fetchrow_hashref();
    $sth->finish();
    
    if ($ref->{'count(*)'} == 0)
    {
	# imei not found
	return 0;
    }
    
    $sql="SELECT * FROM `imei` AS a LEFT JOIN `event` AS b ON a.event_id = b.id LEFT JOIN `opl` AS c ON b.data = c.id WHERE imei='$string'";
    $sth = $dbh->prepare($sql);
    $sth->execute();
    $ref = $sth->fetchrow_hashref();
    $sth->finish();
    my $refCom=$ref->{'ref_com'};
    my $data=$ref->{'data'};

    if ($data == 0)
    {
	# opl not found
	return 1;
    }

    #open(FILE, "<$file");
    #@list = <FILE>;
    
    #foreach $item (@list)
    #{
	#chomp($item);
    
    $refCom=~/([^-]+)(-\d{1}).([^-]+)/;
    $name=$1;
    $customerCountry=$3;
    #print "before grep in isLocked function\n";
    `echo $refCom $name $customerCountry >> refCom`;
    $simlock=`grep $name $file | grep $customerCountry | awk -F "," '{ print \$5 }'`;
    #print $simlock . "\n";
    #print "after grep in isLocked function\n";

    if ($simlock =~m/^NA/ || $simlock =~m/^NON/ || $simlock =~m/^N\/A/ || $simlock =~m/^NO/ || $simlock =~m/^No/ || $simlock =~m/^Non/ || $simlock =~m/^non/)
    {
	# imei not locked
	return 0;
    }	    

    return 1;
}

1;
